const express = require('express');
const axios = require('axios');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

const app = express();
app.use(cors());

// 创建一个用于存放视频文件的目录
const videoDirectory = path.join(__dirname, 'videos');
if (!fs.existsSync(videoDirectory)) {
  fs.mkdirSync(videoDirectory);
}

app.get('/api/proxy', async (req, res) => {
  try {
    // 获取并解码视频 URL 参数
    const videoUrl = decodeURIComponent(req.query.url || '');
    
    // 检查是否提供了有效的 URL
    if (!videoUrl) {
      return res.status(400).send('Video URL is required');
    }

    // 确保 URL 是以 http 或 https 开头的
    if (!/^https?:\/\//i.test(videoUrl)) {
      return res.status(400).send('Invalid video URL format');
    }

    // 使用 axios 发送请求
    const response = await axios({
      method: 'get',
      url: videoUrl,
      responseType: 'arraybuffer',
      timeout: 300000 // 超时设置为1分钟
    });

    // 生成唯一的文件名
    const hash = crypto.createHash('sha256').update(videoUrl).digest('hex');
    // console.log('response.headers', response.headers?.['content-type'], response.headers?.['content-type']?.split('/')?.[1])
    const videoType = response.headers?.['content-type']?.split('/')?.[1] || 'mp4'
    const fileName = `${hash}.${videoType}`;
    const filePath = path.join(videoDirectory, fileName);

    // 将视频文件写入磁盘
    fs.writeFileSync(filePath, response.data);

    // 生成视频播放链接
    const videoLink = `/videos/${fileName}`;

    // 返回视频播放链接
    res.json({code: '200', data: {url: videoLink}, message: 'ok'  });
  } catch (error) {
    console.error(error);
    res.status(500).send('Error fetching resource', error);
  }
});

// 配置静态文件服务
app.use('/videos', express.static(videoDirectory));

const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
  console.log(`Proxy server running on port ${PORT}`);
});